package com.buddy.design.pattern._05strategy0;


import org.springframework.core.annotation.AnnotationUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author buddy
 * @date 2021/9/16
 */
public class OrderService {

    /**
     * key为订单来源，value为对应的订单处理器Handler
     */
    private Map<OrderHandlerType, OrderHandler> orderHandlerMap;

    public void setOrderHandlerMap(List<OrderHandler> orderHandlerList) {
        // 注入各种类型的订单处理类
//        orderHandlerMap = orderHandlerList.stream().collect(
//                Collectors.toMap(orderHandler -> Objects.requireNonNull(AnnotationUtils.findAnnotation(orderHandler.getClass(), OrderHandlerType.class)).source(),
//                        v -> v, (v1, v2) -> v1));
        orderHandlerMap = orderHandlerList.stream().collect(
                Collectors.toMap(orderHandler -> AnnotationUtils.findAnnotation(orderHandler.getClass(), OrderHandlerType.class),
                        v -> v, (v1, v2) -> v1));
    }

    public void orderService(Order order) {

        // ...一些前置处理

        // 通过订单来源确以及支付方式获取对应的handler
        OrderHandlerType orderHandlerType = new OrderHandlerTypeImpl(order.getSource(), order.getPayMethod());
        OrderHandler orderHandler = orderHandlerMap.get(orderHandlerType);
        orderHandler.handle(order);

        // ...一些后置处理
    }
}
